package commands

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
	"golang-manage-admin/http/middles"
	"golang-manage-admin/lib"
	"golang-manage-admin/providers"
	"golang-manage-admin/queue/publish"
	"golang-manage-admin/routers"
)

var ApiCmd = &cobra.Command{
	Use:   "api",
	Short: "Api接口服务",
	Args:  cobra.NoArgs, //没有参数
	//命令执行
	Run: func(cmd *cobra.Command, args []string) {
		app := providers.Config.GetStringMapString("app")
		// 设置对应的模式
		if app["model"] == "release" {
			gin.SetMode(gin.ReleaseMode)
		}
		r := providers.GinEngine
		r.Use(gin.Logger())

		// ===  路由声明 start ====
		api := r.Group("", middles.RecoveryMiddleware())
		routers.NewApis(api)
		// ===  路由声明 end ====

		// 判断是否开启路由打印
		if app["router_log"] == "show" {
			fmt.Printf("Router: %s ", "http://127.0.0.1:"+app["port"])
			fmt.Println()
			lib.PrintRoutesPretty(r, []string{
				"test",
			})
		}

		// 推送队列初始化 --按需求来
		publish.PublishInit()

		// 端口监听
		if port, exist := app["port"]; exist {
			_ = r.Run(":" + port)
		} else {
			_ = r.Run(":8080")
		}
	},
}
